import { BrowserWindow, dialog } from 'electron';
import { asyncChannels } from './asyncChannels'
import IpcMain = Electron.IpcMain

export function dialogListener(window: BrowserWindow) {
    const ipcMain = require('electron').ipcMain;

    showOpenDialog(window, ipcMain, asyncChannels.showOpenDialog)
}

function showOpenDialog(window: BrowserWindow, ipcMain: IpcMain, channel: string) {
    const replyChannel = channel + '-reply'

    ipcMain.on(channel, async (event, uid, options) => {
        let resp;
        let error;
        try {
            resp = await dialog.showOpenDialog(window, options)
        } catch (e) {
            error = e;
        } finally {
            event.sender.send(replyChannel, uid, [resp, error]);
        }
    })
}
